package cn.kilo.domain.support;

import cn.kilo.types.enums.ResponseCode;
import cn.kilo.types.model.Response;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

@Service
@Slf4j
public class OssUploadService {
    @Value("${oss.endpoint}")
    private String endpoint;
    @Value("${oss.accessKey}")
    private String accessKey;
    @Value("${oss.secretKey}")
    private String secretKey;
    @Value("${oss.bucket}")
    private String bucket;
    public String uploadImg(MultipartFile img) throws IOException {
            InputStream inputStream=img.getInputStream();

            //获取文件名，UUID格式
            String originalFileName=img.getOriginalFilename();
            String newFileName= UUID.randomUUID().toString()+originalFileName.substring(originalFileName.lastIndexOf('.'));

            //上传文件
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKey, secretKey);
            ossClient.putObject(bucket,newFileName,inputStream);

            //获取上传后的文件url
            String url = endpoint.split("//")[0] + "//" + bucket + "." + endpoint.split("//")[1] + "/" + newFileName;

            // 关闭ossClient
            ossClient.shutdown();
            return url;
    }

    public String uploadImgByExpiration(MultipartFile img) throws IOException {
        InputStream inputStream=img.getInputStream();

        Date expiration = new Date(System.currentTimeMillis() + 2628000 * 1000L);
        //获取文件名，UUID格式
        String originalFileName=img.getOriginalFilename();
        String newFileName= UUID.randomUUID().toString()+originalFileName.substring(originalFileName.lastIndexOf('.'));

        //上传文件
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKey, secretKey);
        ossClient.putObject(bucket,newFileName,inputStream);

        //获取上传后的文件url
        String url = endpoint.split("//")[0] + "//" + bucket + "." + endpoint.split("//")[1] + "/" + newFileName;
        // 关闭ossClient
        ossClient.shutdown();
        return url;
    }

}
